package ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

import control.ClientConnector.ServiceAction;

public class ServiceWindow implements ActionListener {

	private JFrame frame;
	private JTextField textField;

	private JButton serverButton;
	private JButton chatButton;
	private JButton broadcastButton;
	private String title;

	private ServiceAction sa;

	public void show() {
		this.frame.setVisible(true);
	}

	public JFrame getFrame() {
		return frame;
	}

	public ServiceWindow(ServiceAction sa, String title) {
		this.sa = sa;
		this.title = title;
		initialize();
	}

	private void initialize() {
		frame = new JFrame();
		frame.setResizable(false);
		frame.setBounds(100, 100, 233, 144);
		frame.setTitle(title);

		frame.setDefaultCloseOperation ( JFrame. DO_NOTHING_ON_CLOSE );
		WindowListener windowListener = new WindowAdapter()
		   {
				public void windowClosing ( WindowEvent w ) {
					close();
					makeExit();
		      }
		   };
		frame.addWindowListener( windowListener );
		
		frame.getContentPane().setLayout(null);
		
		this.serverButton = new JButton("Server Chat");
		this.serverButton.addActionListener(this);
		this.serverButton.setBounds(10, 11, 206, 23);
		frame.getContentPane().add(this.serverButton);
		
		this.chatButton = new JButton("Client Chat");
		this.chatButton.addActionListener(this);
		this.chatButton.setBounds(106, 78, 110, 23);
		frame.getContentPane().add(this.chatButton);
		
		textField = new JTextField();
		textField.setBounds(10, 79, 86, 20);
		frame.getContentPane().add(textField);
		textField.setColumns(10);
		
		broadcastButton = new JButton("Bate-Papo");
		this.broadcastButton.addActionListener(this);
		broadcastButton.setBounds(10, 45, 206, 23);
		frame.getContentPane().add(broadcastButton);
	}

	private void makeExit() {
		sa.close();
	}
	
	public void close() {
		frame.setVisible( false );
		frame.dispose();
	}

	public void actionPerformed(ActionEvent e) {
		try {
		    if (e.getSource() == this.serverButton) {
		    	sa.makeServer();
		    } else if (e.getSource() == this.chatButton) {
		    	String s = textField.getText().trim();

		    	if(!s.equals("")) {
		    		sa.makeChat(textField.getText());
		    		textField.setText("");
		    	}
		    } else if(e.getSource() == this.broadcastButton) {
		    	sa.makeBroadcast();
		    }
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}
